<template>
  <a-layout class="container">
    <a-layout-sider class="layout-sider">
      <a-card class="stats-card">
        <div class="stat-item"></div>
        <div class="stat-item">微信: {{ device.deviceWxName }}</div>
        <template #title>
          统计信息
        </template>
        <div class="stat-item">总消息数: {{ statistics.total }}</div>
        <div class="stat-item">活跃群组: {{ statistics.activeGroups }}</div>
        <div class="stat-item">今日消息: {{ statistics.today }}</div>
      </a-card>

      <a-card class="group-card">
        <template #title>
          聊天列表
        </template>
        <a-list :data="groups">
          <template #item="{ item }">
            <a-list-item
              class="group-item"
              :class="{ 'active': activeGroup === (item.senderRoomId || item.senderWxId) }"
              @click="switchGroup(item)"
            >
              {{ item.senderRoomName || item.senderUserName }}
            </a-list-item>
          </template>
        </a-list>
      </a-card>
    </a-layout-sider>

    <a-layout-content class="layout-content">
      <div class="chat-header">
        <div class="header-left">
          <h3>{{ currentGroup.senderRoomName || currentGroup.senderUserName }}</h3>
        </div>
        <a-button type="primary" @click="refreshMessages">刷新</a-button>
      </div>

      <div class="chat-content">
        <div
          v-for="(msg, index) in currentMessages"
          :key="index"
          class="message-item"
          :class="{
            'right-message': msg.senderWxId === device.deviceWxId,
            'left-message': msg.senderWxId !== device.deviceWxId
          }"
        >
          <span class="username">{{ msg.senderUserName }}:</span>
          <span class="content">{{ msg.content }}</span>
          <span class="time">{{ msg.time }}</span>
        </div>
      </div>
    </a-layout-content>
  </a-layout>
</template>

<script setup>
  import { reactive, ref, computed, onMounted } from "vue";
  import router from '@/router'
  
  const statistics = reactive({
    total: 0,
    activeGroups: 0,
    today: 0
  });
  
  // 定义 reactive 对象来存储设备信息
  const device = reactive({
    deviceWxId: "",
    deviceWxName: ""
  });

  const props = defineProps({
    deviceWxId: String,
    deviceWxName: String
  });

  // 在组件挂载时从路由查询参数中获取数据并赋值给 device
  const initDeviceParam = () => {
    if (props.deviceWxId) {
      device.deviceWxId = props.deviceWxId;
    }
    if (props.deviceWxName) {
      device.deviceWxName = props.deviceWxName;
    }
  }
  const getWebsocket = () => {
    var ws = new WebSocket("ws://localhost:8888/webSocket");

    ws.onopen = () => {
      console.log("网络连接成功");
      ws.send(JSON.stringify({ deviceWxId: device.deviceWxId }));
    };

    ws.onmessage = (e) => {
      try {
        const data = JSON.parse(e.data);
        const items = Array.isArray(data) ? data : [data];

        items.forEach(rawData => {
          if (!rawData.content || !rawData.senderWxId) return;

          const isGroup = !!rawData.senderRoomId;

          // 更新群组/用户列表
          if (isGroup) {
            const existingIndex = groups.findIndex(g => g.senderRoomId === rawData.senderRoomId);
            if (existingIndex !== -1) {
              // 更新群组名称
              groups[existingIndex].senderRoomName = rawData.senderRoomName;
            } else {
              groups.push({
                senderRoomId: rawData.senderRoomId,
                senderRoomName: rawData.senderRoomName,
                senderWxId: null,
                senderUserName: null
              });
            }
          } else {
            const existingIndex = groups.findIndex(g =>
              g.senderWxId === rawData.senderWxId && !g.senderRoomId
            );
            if (existingIndex !== -1) {
              // 更新用户名称
              groups[existingIndex].senderUserName = rawData.senderUserName;
            } else {
              groups.push({
                senderWxId: rawData.senderWxId,
                senderUserName: rawData.senderUserName || `用户${rawData.senderWxId.slice(-4)}`,
                senderRoomId: null,
                senderRoomName: null
              });
            }
          }

          messages.push(rawData);
        });

      } catch (error) {
        console.error("消息处理失败:", error);
      }
    };
  };

  onMounted(() => {
    initDeviceParam();
    getWebsocket();
  });

  const groups = reactive([
    { senderWxId: null, senderUserName: null, senderRoomId: "room1", senderRoomName: "模拟群名称" }
  ]);

  const messages = reactive([
    {
      content: "hello world",
      time: "10:00",
      senderWxId: "18248562561",
      senderUserName: "我是机器人",
      senderRoomId: "room1",
      senderRoomName: "模拟联系人"
    }
  ]);

  const activeGroup = ref(groups[0].senderRoomId || groups[0].senderWxId);
  const currentGroup = reactive({ ...groups[0] });

  const currentMessages = computed(() => {
    return messages.filter(msg =>
      (currentGroup.senderRoomId && msg.senderRoomId === currentGroup.senderRoomId) ||
      (currentGroup.senderWxId && msg.senderWxId === currentGroup.senderWxId && !msg.senderRoomId)
    );
  });

  function initCurrentGroup() {
    const group = groups.find(g =>
      g.senderRoomId === activeGroup.value ||
      g.senderWxId === activeGroup.value
    );
    if (group) Object.assign(currentGroup, group);
  }

  initCurrentGroup();

  function switchGroup(group) {
    activeGroup.value = group.senderRoomId || group.senderWxId;
    Object.assign(currentGroup, group);
  }

  function refreshMessages() {
    // 刷新逻辑
  }
</script>

<style scoped>
    .container {
        height: 100vh;
        padding: 20px;
        background: #f5f5f5;
    }

    .layout-sider {
        background: transparent;
        margin-right: 20px;
    }

    .layout-content {
        background: #fff;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .stats-card, .group-card {
        margin-bottom: 20px;
        border-radius: 8px;
    }

    .card-icon {
        margin-right: 8px;
        color: #1890ff;
    }

    .stat-item {
        margin: 8px 0;
        color: #666;
    }

    .group-item {
        cursor: pointer;
        padding: 12px;
        transition: all 0.3s;
        position: relative;
    }

    .group-item:hover {
        background: #f0f9ff;
    }

    .active {
        background: #e6f7ff;
        font-weight: bold;
    }


    .chat-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px;
        border-bottom: 1px solid #eee;
    }

    .chat-content {
        height: calc(100vh - 160px);
        overflow-y: auto;
        padding: 16px;
    }

    .message-item {
        margin: 12px 0;
        padding: 8px 12px;
        background: #f8f8f8;
        border-radius: 4px;
        display: flex;
        align-items: center;
    }

    .username {
        color: #1890ff;
        margin-right: 8px;
        font-weight: 500;
    }

    .time {
        margin-left: auto;
        color: #999;
        font-size: 0.8em;
    }

    .left-message {
        color: #0a0101;
    }

    .right-message {
        color: rgb(116, 2, 255);
    }
</style>
